import { CCUtils } from "../Framework/scripts/CCUtils";
import { Toolkit } from "../Framework/scripts/Toolkit";
import ViewOrientation, { EOrientation } from "../Framework/scripts/ViewOrientation";
import Watcher from "../Framework/scripts/Watcher";
import CookingTiledom from "./CookingTiledom";
import Item from "./Item";
import ItemPanel from "./ItemPanel";
const { ccclass, property } = cc._decorator;

@ccclass
export default class ItemFactory extends cc.Component {

    @property(cc.Node)
    top: cc.Node = null;
    @property(cc.Node)
    bottom: cc.Node = null;

    @property(cc.Node)
    slot: cc.Node = null;
    @property(cc.Node)
    slotBG: cc.Node = null;

    /** 6x5 */
    onLoad() {
        Watcher.on(CookingTiledom.EVENT_CREATE_ITEM, this, this.setDesktop);
        Watcher.on(ItemPanel.EVENT_FLY_ITEM, this, this.removeItem);


        let srcWidget = this.node.getComponent(cc.Widget);
        let slotWidget = this.slot.getComponent(cc.Widget);
        let slotBGWidget = this.slotBG.getComponent(cc.Widget);
        Watcher.on(ViewOrientation.ON_VIEW_RESIZE, this, (e) => {

            if (e.dir === EOrientation.LANDSCAPE) {
                this.top.active = false;
                this.bottom.active = false;
                srcWidget.verticalCenter = 50;

                slotWidget.isAlignVerticalCenter = false;
                slotWidget.isAlignBottom = true;
                slotWidget.bottom = 0;

                slotBGWidget.isAlignVerticalCenter = false;
                slotBGWidget.isAlignBottom = true;
                slotBGWidget.bottom = 0;
            }
            else {
                this.top.active = true;
                this.bottom.active = true;
                srcWidget.verticalCenter = 0;

                slotWidget.isAlignBottom = false;
                slotWidget.isAlignVerticalCenter = true;
                slotBGWidget.isAlignBottom = false;
                slotBGWidget.isAlignVerticalCenter = true;

            }

            // if(e.dir ===EOrientation.LANDSCAPE){
            //     this.node.scale = 0.6;
            // }
            // else{
            //     this.node.scale = 1.0;
            // }
        });
    }

    /** 设置桌面 */
    setDesktop(config, itemprefab: cc.Prefab) {

        if (config.type === 'custom') {
            this.isCustom = true;
            setTimeout(() => {
                this.initCustom(config, itemprefab);
            }, 500);
        }
        else {
            //初始化关卡道具
            this.initItems(config);
            //随机生成测试
            this.randomSpawn(itemprefab);
        }
    }

    customItems = [];
    initCustom(config, itemprefab) {

        let _w = this.node.width / 6;
        let _h = this.node.height / 5;
        this.unit_w = _w;
        this.unit_h = _h;

        let i = 0;
        let j = 0;
        const max = config.layers.length;
        const layers = config.layers;
        setTimeout(() => {
            this.gameReady();
        }, 340);
        var id = setInterval(() => {

            if (i >= max) {
                clearInterval(id);
                setTimeout(() => {
                    this.maskLayer.removeFromParent();
                    //this.refreshState();
                }, 300);
                this.gameGo();
                return;
            }
            //console.log("下饺子咯");

            let layer = layers[i];
            if (j >= layer.length) {
                j = 0;
                i++;
                return;
            }
            let e = layer[j];
            let inst = cc.instantiate(itemprefab);
            this.addCustomItem(inst, e.x, e.y, parseInt(e.gid), i);
            j++;
        }, 50);
    }

    @property(cc.Node)
    ready: cc.Node = null;
    @property(cc.Node)
    go: cc.Node = null;
    @property(cc.Node)
    maskLayer: cc.Node;
    gameGo() {
        cc.tween(this.go).to(1.0, { scale: 1.0 }, cc.easeElasticOut(0.4)).to(
            0.2, { scale: 0 }
        ).call(() => { this.go.removeFromParent(); }).start();
    }
    gameReady() {

        cc.tween(this.ready).to(1.0, {
            y: 0
        }, cc.easeElasticOut(0.3)).to(0.2, { opacity: 0 }).call(() => {
            this.ready.removeFromParent();
        }).start();

    }


    items = [];
    isFirst = false;
    isCustom = false;
    initItems(config) {
        this.items = [];
        let weight = config.weight;
        let sum = config.sum;
        let items = config.item_list;
        this.isFirst = config.first;

        for (let id in items) {
            let num = Math.ceil(items[id] * sum / weight);
            while (num % 3 != 0) ++num;
            let gid = parseInt(id);
            for (let i = 0; i < num; i++)
                this.items.push(gid);
        }

        let len = this.items.length - 36;
        for (let i = 0; i < len; i++) this.items.pop();
        Toolkit.logTrace(`初始化配置成功 道具总数: ${this.items.length}`);
    }


    //获取道具
    getItem() {
        let randomIndex = Toolkit.RandomInt(this.items.length);
        let id = this.items.splice(randomIndex, 1)[0];
        return id;
    }

    unit_w = 0;
    unit_h = 0;
    //随机生成
    randomSpawn(itemprefab) {

        let _w = this.node.width / 6;
        let _h = this.node.height / 5;
        this.unit_w = _w;
        this.unit_h = _h;
        let _top = (this.node.height - _h) * 0.5;
        let _left = (-this.node.width + _w) * 0.5;

        //外边框向中心生成
        for (let i = 0, _i = 5; i < _i; i++, _i--) {
            for (let j = 0, _j = 4; j < _j; j++, _j--) {
                //左上
                let inst = cc.instantiate(itemprefab);
                this.addItem(_left, _top, _w, _h, i, j, inst);
                //右下
                inst = cc.instantiate(itemprefab);
                this.addItem(_left, _top, _w, _h, _i, _j, inst);
                //左下
                inst = cc.instantiate(itemprefab);
                this.addItem(_left, _top, _w, _h, i, _j, inst);
                //右下
                inst = cc.instantiate(itemprefab);
                this.addItem(_left, _top, _w, _h, _i, j, inst);
            }
        }
        //中间横排
        for (let i = 0; i < 6; i++) {
            let inst = cc.instantiate(itemprefab);
            this.addItem(_left, _top, _w, _h, i, 2, inst);
        }

        //第二层
        _top = this.itemMap[0][1][1].node.y - _h * 0.5;
        _left = this.itemMap[0][1][1].node.x + _w * 0.5;
        for (let i = 0; i < 3; i++) {
            for (let j = 0; j < 2; j++) {
                let inst = cc.instantiate(itemprefab);
                this.addItem(_left, _top, _w, _h, i, j, inst, 1);
                inst.zIndex = 2;
            }
        }
        this.refreshState();

        Toolkit.logTrace(`Item创建完成: ${this.node.childrenCount}`);
    }

    refreshLock = false;
    refreshState() {
        if (this.refreshLock) return;
        this.refreshLock = true;
        const bound_r = (this.unit_h + this.unit_w) * 0.5;

        if (this.isCustom) {

            for (let i = this.customItems.length - 1; i > 0; i--) {
                const layer1 = this.customItems[i - 1]; //底层
                const layer2 = this.customItems[i];//高层

                for (let e of layer1) e.interaction = true;
                for (let e2 of layer2) {
                    for (let e of layer1) {
                        if (CCUtils.distance(e2.node, e.node) <= bound_r) {
                            e.interaction = false;
                            this.refreshLock = false;
                        }
                    }
                }
            }
            return;
        }


        const items1 = this.itemMap[0];
        const items2 = this.itemMap[1];
        //底层
        for (let lines1 of items1) {
            for (let item1 of lines1) {
                item1.interaction = true;
            }
        }

        //上层
        for (let lines of items2) {
            for (let item of lines) {

                //底层
                for (let lines1 of items1) {
                    for (let item1 of lines1) {

                        if (CCUtils.distance(item1.node, item.node) <= bound_r) {
                            item1.interaction = false;
                            this.refreshLock = false;
                        }
                    }
                }

            }
        }
    }

    removeItem(item: Item) {

        if (this.node.childrenCount === 1) {
            Watcher.dispatch(CookingTiledom.EVENT_GAME_END);
        }

        if (this.isCustom) {
            this.customItems[item.layer].splice(
                this.customItems[item.layer].indexOf(item), 1
            );
        }
        else {

            this.itemMap[item.layer][item.coord.y].splice(
                this.itemMap[item.layer][item.coord.y].indexOf(item), 1
            );

        }

        setTimeout(() => {
            this.refreshState();
        }, 200);
    }

    addCustomItem(inst: cc.Node, x, y, icon, layer = 0) {
        this.node.addChild(inst);
        let s: Item = inst.getComponent(Item);
        s.setIcon(icon);
        s.layer = layer;

        inst.setPosition(x, y + cc.view.getVisibleSize().height * 0.5);
        cc.tween(inst).to(0.4, { y: y }, cc.easeElasticOut(0.618)).call(() => {
            if (layer > 0)
                this.refreshState();
        }).start();

        if (!this.customItems[layer]) this.customItems[layer] = [];
        this.customItems[layer].push(s);
    }

    itemMap: Array<Array<Array<Item>>> = [];
    addItem(_left, _top, _w, _h, i, j, inst, layer = 0) {

        this.node.addChild(inst);
        inst.x = _left + i * _w;
        inst.y = _top - j * _h;

        let s: Item = inst.getComponent(Item);
        s.setIcon(this.getItem());

        s.layer = layer;
        s.coord = { x: i, y: j };
        if (!this.itemMap[layer]) {
            this.itemMap[layer] = [];
        }
        if (!this.itemMap[layer][j]) {
            this.itemMap[layer][j] = [];
        }
        this.itemMap[layer][j][i] = s;
    }

}
